import type { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { clone } from 'element-plus-extension/es/shared';
import { store } from '../index';
import { asyncRoutes, constantRoutes } from '@/plugins/router/staticRoutes';
import { flatMultiLevelRoutes, generateRoutesByFrontEnd, generateRoutesByServer } from '@/utils/routerUtils';

export interface PermissionState {
  routes: RouteRecordRaw[];
  addRoutes: RouteRecordRaw[];
  isLoadedRoutes: boolean;
  columnMenuRoutes: RouteRecordRaw[];
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routes: [],
    addRoutes: [],
    isLoadedRoutes: false,
    columnMenuRoutes: []
  }),
  getters: {
    getRoutes(): RouteRecordRaw[] {
      return this.routes;
    },
    getAddRoutes(): RouteRecordRaw[] {
      return flatMultiLevelRoutes(clone(this.addRoutes, true));
    },
    getIsLoadedRoutes(): boolean {
      return this.isLoadedRoutes;
    },
    getColumnMenuRoutes(): RouteRecordRaw[] {
      return this.columnMenuRoutes;
    }
  },
  actions: {
    generateRoutes(type: 'server' | 'frontEnd' | 'static', routes: RouteRecordRaw[] | string[]) {
      return new Promise<RouteRecordRaw[]>((resolve) => {
        let routerMap: RouteRecordRaw[] = [];
        if (type === 'server') {
          // 模拟后端过滤菜单
          routerMap = generateRoutesByServer(routes as RouteRecordRaw[]);
        } else if (type === 'frontEnd') {
          // 模拟前端过滤菜单
          routerMap = generateRoutesByFrontEnd(asyncRoutes, routes as string[]);
        }
        // 动态路由，404一定要放到最后面
        this.addRoutes = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ]);
        // 渲染菜单的所有路由
        this.routes = clone(constantRoutes, true).concat(routerMap);
        resolve(routerMap);
      });
    },
    setIsLoadedRoutes(state: boolean): void {
      this.isLoadedRoutes = state;
    },
    setColumnMenuRoutes(routes: RouteRecordRaw[]): void {
      this.columnMenuRoutes = routes;
    },
    reset() {
      this.isLoadedRoutes = false;
      this.routes = [];
      this.addRoutes = [];
      this.columnMenuRoutes = [];
    }
  }
});

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store);
};
